导航菜单
首页 >  Bundling Assets with Laravel Vite  > Asset Bundling (Vite) – Laravel Documentation – \Cornch\Docs::class

Asset Bundling (Vite) – Laravel Documentation – \Cornch\Docs::class

Deprecated versionYou are viewing a deprecated version of Laravel Documentation. This version no longer receives bug fixes and security updates. You can switch the version from the sidebar.If you are using this version, you should upgrade to the latest version as soon as possible.The current version of Laravel Framework is 10.x.

Asset Bundling (Vite)IntroductionInstallation & SetupInstalling NodeInstalling Vite And The Laravel PluginConfiguring ViteLoading Your Scripts And StylesRunning ViteWorking With JavaScriptAliasesVueReactInertiaURL ProcessingWorking With StylesheetsWorking With Blade & RoutesProcessing Static Assets With ViteRefreshing On SaveAliasesCustom Base URLsEnvironment VariablesDisabling Vite In TestsServer-Side Rendering (SSR)Script & Style Tag AttributesContent Security Policy (CSP) NonceSubresource Integrity (SRI)Arbitrary AttributesAdvanced CustomizationCorrecting Dev Server URLsIntroduction

Vite is a modern frontend build tool that provides an extremely fast development environment and bundles your code for production. When building applications with Laravel, you will typically use Vite to bundle your application's CSS and JavaScript files into production ready assets.

Laravel integrates seamlessly with Vite by providing an official plugin and Blade directive to load your assets for development and production.

lightbulb

Are you running Laravel Mix? Vite has replaced Laravel Mix in new Laravel installations. For Mix documentation, please visit the Laravel Mix website. If you would like to switch to Vite, please see our migration guide.

Choosing Between Vite And Laravel Mix

Before transitioning to Vite, new Laravel applications utilized Mix, which is powered by webpack, when bundling assets. Vite focuses on providing a faster and more productive experience when building rich JavaScript applications. If you are developing a Single Page Application (SPA), including those developed with tools like Inertia, Vite will be the perfect fit.

Vite also works well with traditional server-side rendered applications with JavaScript "sprinkles", including those using Livewire. However, it lacks some features that Laravel Mix supports, such as the ability to copy arbitrary assets into the build that are not referenced directly in your JavaScript application.

Migrating Back To Mix

Have you started a new Laravel application using our Vite scaffolding but need to move back to Laravel Mix and webpack? No problem. Please consult our official guide on migrating from Vite to Mix.

Installation & Setuplightbulb

The following documentation discusses how to manually install and configure the Laravel Vite plugin. However, Laravel's starter kits already include all of this scaffolding and are the fastest way to get started with Laravel and Vite.

Installing Node

You must ensure that Node.js (16+) and NPM are installed before running Vite and the Laravel plugin:

1node -v2npm -v1node -v2npm -v

You can easily install the latest version of Node and NPM using simple graphical installers from the official Node website. Or, if you are using Laravel Sail, you may invoke Node and NPM through Sail:

1./vendor/bin/sail node -v2./vendor/bin/sail npm -v1./vendor/bin/sail node -v2./vendor/bin/sail npm -vInstalling Vite And The Laravel Plugin

Within a fresh installation of Laravel, you will find a package.json file in the root of your application's directory structure. The default package.json file already includes everything you need to get started using Vite and the Laravel plugin. You may install your application's frontend dependencies via NPM:

1npm install1npm installConfiguring Vite

Vite is configured via a vite.config.js file in the root of your project. You are free to customize this file based on your needs, and you may also install any other plugins your application requires, such as @vitejs/plugin-vue or @vitejs/plugin-react.

The Laravel Vite plugin requires you to specify the entry points for your application. These may be JavaScript or CSS files, and include preprocessed languages such as TypeScript, JSX, TSX, and Sass.

1import { defineConfig } from 'vite'; 2import laravel from 'laravel-vite-plugin'; 3  4export default defineConfig({ 5plugins: [ 6laravel([ 7'resources/css/app.css', 8'resources/js/app.js', 9]),10],11}); 1import { defineConfig } from 'vite'; 2import laravel from 'laravel-vite-plugin'; 3  4export default defineConfig({ 5plugins: [ 6laravel([ 7'resources/css/app.css', 8'resources/js/app.js', 9]),10],11});

If you are building an SPA, including applications built using Inertia, Vite works best without CSS entry points:

1import { defineConfig } from 'vite'; 2import laravel from 'laravel-vite-plugin'; 3  4export default defineConfig({ 5plugins: [ 6laravel([ 7'resources/css/app.css', 8'resources/js/app.js', 9]),10],11}); 1import { defineConfig } from 'vite'; 2import laravel from 'laravel-vite-plugin'; 3  4export default defineConfig({ 5plugins: [ 6laravel([ 7'resources/css/app.css', 8'resources/js/app.js', 9]),10],11});

Instead, you should import your CSS via JavaScript. Typically, this would be done in your application's resources/js/app.js file:

1import './bootstrap';2import '../css/app.css'; 1import './bootstrap';2import '../css/app.css';

The Laravel plugin also supports multiple entry points and advanced configuration options such as SSR entry points.

Working With A Secure Development Server

If your local development web server is serving your application via HTTPS, you may run into issues connecting to the Vite development server.

If you are using Laravel Valet for local development and have run the secure command against your application, you may configure the Vite development server to automatically use Valet's generated TLS certificates:

1import { defineConfig } from 'vite'; 2import laravel from 'laravel-vite-plugin'; 3  4export default defineConfig({ 5plugins: [ 6laravel({ 7// ... 8valetTls: 'my-app.test', 9}),10],11}); 1import { defineConfig } from 'vite'; 2import laravel from 'laravel-vite-plugin'; 3  4export default defineConfig({ 5plugins: [ 6laravel({ 7// ... 8valetTls: 'my-app.test', 9}),10],11});

When using another web server, you should generate a trusted certificate and manually configure Vite to use the generated certificates:

1// ... 2import fs from 'fs'; 3  4const host = 'my-app.test'; 5  6export default defineConfig({ 7// ... 8server: { 9host, 10hmr: { host }, 11https: { 12key: fs.readFileSync(`/path/to/${host}.key`), 13cert: fs.readFileSync(`/path/to/${host}.crt`), 14}, 15}, 16}); 1// ... 2import fs from 'fs'; 3  4const host = 'my-app.test'; 5  6export default defineConfig({ 7// ... 8server: { 9host, 10hmr: { host }, 11https: { 12key: fs.readFileSync(`/path/to/${host}.key`), 13cert: fs.readFileSync(`/path/to/${host}.crt`), 14}, 15}, 16});

If you are unable to generate a trusted certificate for your system, you may install and configure the @vitejs/plugin-basic-ssl plugin. When using untrusted certificates, you will need to accept the certificate warning for Vite's development server in your browser by following the "Local" link in your console when running the npm run dev command.

Loading Your Scripts And Styles

With your Vite entry points configured, you only need reference them in a @vite() Blade directive that you add to the of your application's root template:

1doctype html>23{{-- ... --}}4 5@vite(['resources/css/app.css', 'resources/js/app.js'])61doctype html>23{{-- ... --}}4 5@vite(['resources/css/app.css', 'resources/js/app.js'])6

If you're importing your CSS via JavaScript, you only need to include the JavaScript entry point:

1doctype html>23{{-- ... --}}4 5@vite('resources/js/app.js')61doctype html>23{{-- ... --}}4 5@vite('resources/js/app.js')6

The @vite directive will automatically detect the Vite development server and inject the Vite client to enable Hot Module Replacement. In build mode, the directive will load your compiled and versioned assets, including any imported CSS.

If needed, you may also specify the build path of your compiled assets when invoking the @vite directive:

1doctype html>23{{-- Given build path is relative to public path. --}}4 5@vite('resources/js/app.js', 'vendor/courier/build')61doctype html>23{{-- Given build path is relative to public path. --}}4 5@vite('resources/js/app.js', 'vendor/courier/build')6Running Vite

There are two ways you can run Vite. You may run the development server via the dev command, which is useful while developing locally. The development server will automatically detect changes to your files and instantly reflect them in any open browser windows.

Or, running the build command will version and bundle your application's assets and get them ready for you to deploy to production:

1# Run the Vite development server...2npm run dev3 4# Build and version the assets for production...5npm run build1# Run the Vite development server...2npm run dev3 4# Build and version the assets for production...5npm run buildWorking With JavaScriptAliases

By default, The Laravel plugin provides a common alias to help you hit the ground running and conveniently import your application's assets:

1{2'@' => '/resources/js'3}1{2'@' => '/resources/js'3}

You may overwrite the '@' alias by adding your own to the vite.config.js configuration file:

1import { defineConfig } from 'vite'; 2import laravel from 'laravel-vite-plugin'; 3  4export default defineConfig({ 5plugins: [ 6laravel(['resources/ts/app.tsx']), 7], 8resolve: { 9alias: {10'@': '/resources/ts',11},12},13}); 1import { defineConfig } from 'vite'; 2import laravel from 'laravel-vite-plugin'; 3  4export default defineConfig({ 5plugins: [ 6laravel(['resources/ts/app.tsx']), 7], 8resolve: { 9alias: {10'@': '/resources/ts',11},12},13});Vue

If you would like to build your front-end using the Vue framework, then you will also need to install the @vitejs/plugin-vue plugin:

1npm install --save-dev @vitejs/plugin-vue1npm install --save-dev @vitejs/plugin-vue

You may then include the plugin in your vite.config.js configuration file. There are a few additional options you will need when using the Vue plugin with Laravel:

1import { defineConfig } from 'vite'; 2import laravel from 'laravel-vite-plugin'; 3import vue from '@vitejs/plugin-vue'; 4  5export default defineConfig({ 6plugins: [ 7laravel(['resources/js/app.js']), 8vue({ 9template: {10transformAssetUrls: {11// The Vue plugin will re-write asset URLs, when referenced12// in Single File Components, to point to the Laravel web13// server. Setting this to `null` allows the Laravel plugin14// to instead re-write asset URLs to point to the Vite15// server instead.16base: null,17 18// The Vue plugin will parse absolute URLs and treat them19// as absolute paths to files on disk. Setting this to20// `false` will leave absolute URLs un-touched so they can21// reference assets in the public directory as expected.22includeAbsolute: false,23},24},25}),26],27}); 1import { defineConfig } from 'vite'; 2import laravel from 'laravel-vite-plugin'; 3import vue from '@vitejs/plugin-vue'; 4  5export default defineConfig({ 6plugins: [ 7laravel(['resources/js/app.js']), 8vue({ 9template: {10transformAssetUrls: {11// The Vue plugin will re-write asset URLs, when referenced12// in Single File Components, to point to the Laravel web13// server. Setting this to `null` allows the Laravel plugin14// to instead re-write asset URLs to point to the Vite15// server instead.16base: null,17 18// The Vue plugin will parse absolute URLs and treat them19// as absolute paths to files on disk. Setting this to20// `false` will leave absolute URLs un-touched so they can21// reference assets in the public directory as expected.22includeAbsolute: false,23},24},25}),26],27});lightbulb

Laravel's starter kits already include the proper Laravel, Vue, and Vite configuration. Check out Laravel Breeze for the fastest way to get started with Laravel, Vue, and Vite.

React

If you would like to build your front-end using the React framework, then you will also need to install the @vitejs/plugin-react plugin:

1npm install --save-dev @vitejs/plugin-react1npm install --save-dev @vitejs/plugin-react

You may then include the plugin in your vite.config.js configuration file:

1import { defineConfig } from 'vite'; 2import laravel from 'laravel-vite-plugin'; 3import react from '@vitejs/plugin-react'; 4  5export default defineConfig({ 6plugins: [ 7laravel(['resources/js/app.jsx']), 8react(), 9],10}); 1import { defineConfig } from 'vite'; 2import laravel from 'laravel-vite-plugin'; 3import react from '@vitejs/plugin-react'; 4  5export default defineConfig({ 6plugins: [ 7laravel(['resources/js/app.jsx']), 8react(), 9],10});

You will need to ensure that any files containing JSX have a .jsx or .tsx extension, remembering to update your entry point, if required, as shown above.

You will also need to include the additional @viteReactRefresh Blade directive alongside your existing @vite directive.

1@viteReactRefresh2@vite('resources/js/app.jsx')1@viteReactRefresh2@vite('resources/js/app.jsx')

The @viteReactRefresh directive must be called before the @vite directive.

lightbulb

Laravel's starter kits already include the proper Laravel, React, and Vite configuration. Check out Laravel Breeze for the fastest way to get started with Laravel, React, and Vite.

Inertia

The Laravel Vite plugin provides a convenient resolvePageComponent function to help you resolve your Inertia page components. Below is an example of the helper in use with Vue 3; however, you may also utilize the function in other frameworks such as React:

1import { createApp, h } from 'vue'; 2import { createInertiaApp } from '@inertiajs/vue3'; 3import { resolvePageComponent } from 'laravel-vite-plugin/inertia-helpers'; 4  5createInertiaApp({ 6 resolve: (name) => resolvePageComponent(`./Pages/${name}.vue`, import.meta.glob('./Pages/**/*.vue')), 7 setup({ el, App, props, plugin }) { 8return createApp({ render: () => h(App, props) }) 9 .use(plugin)10 .mount(el)11 },12}); 1import { createApp, h } from 'vue'; 2import { createInertiaApp } from '@inertiajs/vue3'; 3import { resolvePageComponent } from 'laravel-vite-plugin/inertia-helpers'; 4  5createInertiaApp({ 6 resolve: (name) => resolvePageComponent(`./Pages/${name}.vue`, import.meta.glob('./Pages/**/*.vue')), 7 setup({ el, App, props, plugin }) { 8return createApp({ render: () => h(App, props) }) 9 .use(plugin)10 .mount(el)11 },12});lightbulb

Laravel's starter kits already include the proper Laravel, Inertia, and Vite configuration. Check out Laravel Breeze for the fastest way to get started with Laravel, Inertia, and Vite.

URL Processing

When using Vite and referencing assets in your application's HTML, CSS, or JS, there are a couple of caveats to consider. First, if you reference assets with an absolute path, Vite will not include the asset in the build; therefore, you should ensure that the asset is available in your public directory.

When referencing relative asset paths, you should remember that the paths are relative to the file where they are referenced. Any assets referenced via a relative path will be re-written, versioned, and bundled by Vite.

Consider the following project structure:

1public/2 taylor.png3resources/4 js/5Pages/6 Welcome.vue7 images/8abigail.png1public/2 taylor.png3resources/4 js/5Pages/6 Welcome.vue7 images/8abigail.png

The following example demonstrates how Vite will treat relative and absolute URLs:

123 45123 45Working With Stylesheets

You can learn more about Vite's CSS support within the Vite documentation. If you are using PostCSS plugins such as Tailwind, you may create a postcss.config.js file in the root of your project and Vite will automatically apply it:

1module.exports = {2plugins: {3tailwindcss: {},4autoprefixer: {},5},6};1module.exports = {2plugins: {3tailwindcss: {},4autoprefixer: {},5},6};Working With Blade & RoutesProcessing Static Assets With Vite

When referencing assets in your JavaScript or CSS, Vite automatically processes and versions them. In addition, when building Blade based applications, Vite can also process and version static assets that you reference solely in Blade templates.

However, in order to accomplish this, you need to make Vite aware of your assets by importing the static assets into the application's entry point. For example, if you want to process and version all images stored in resources/images and all fonts stored in resources/fonts, you should add the following in your application's resources/js/app.js entry point:

1import.meta.glob([2 '../images/**',3 '../fonts/**',4]);1import.meta.glob([2 '../images/**',3 '../fonts/**',4]);

These assets will now be processed by Vite when running npm run build. You can then reference these assets in Blade templates using the Vite::asset method, which will return the versioned URL for a given asset:

11Refreshing On Save

When your application is built using traditional server-side rendering with Blade, Vite can improve your development workflow by automatically refreshing the browser when you make changes to view files in your application. To get started, you can simply specify the refresh option as true.

1import { defineConfig } from 'vite'; 2import laravel from 'laravel-vite-plugin'; 3  4export default defineConfig({ 5plugins: [ 6laravel({ 7// ... 8refresh: true, 9}),10],11}); 1import { defineConfig } from 'vite'; 2import laravel from 'laravel-vite-plugin'; 3  4export default defineConfig({ 5plugins: [ 6laravel({ 7// ... 8refresh: true, 9}),10],11});

When the refresh option is true, saving files in the following directories will trigger the browser to perform a full page refresh while you are running npm run dev:

app/View/Components/**lang/**resources/lang/**resources/views/**routes/**

Watching the routes/** directory is useful if you are utilizing Ziggy to generate route links within your application's frontend.

If these default paths do not suit your needs, you can specify your own list of paths to watch:

1import { defineConfig } from 'vite'; 2import laravel from 'laravel-vite-plugin'; 3  4export default defineConfig({ 5plugins: [ 6laravel({ 7// ... 8refresh: ['resources/views/**'], 9}),10],11}); 1import { defineConfig } from 'vite'; 2import laravel from 'laravel-vite-plugin'; 3  4export default defineConfig({ 5plugins: [ 6laravel({ 7// ... 8refresh: ['resources/views/**'], 9}),10],11});

Under the hood, the Laravel Vite plugin uses the vite-plugin-full-reload package, which offers some advanced configuration options to fine-tune this feature's behavior. If you need this level of customization, you may provide a config definition:

1import { defineConfig } from 'vite'; 2import laravel from 'laravel-vite-plugin'; 3  4export default defineConfig({ 5plugins: [ 6laravel({ 7// ... 8refresh: [{ 9paths: ['path/to/watch/**'],10config: { delay: 300 }11}],12}),13],14}); 1import { defineConfig } from 'vite'; 2import laravel from 'laravel-vite-plugin'; 3  4export default defineConfig({ 5plugins: [ 6laravel({ 7// ... 8refresh: [{ 9paths: ['path/to/watch/**'],10config: { delay: 300 }11}],12}),13],14});Aliases

It is common in JavaScript applications to create aliases to regularly referenced directories. But, you may also create aliases to use in Blade by using the macro method on the Illuminate\Support\Facades\Vite class. Typically, "macros" should be defined within the boot method of a service provider:

1/**2 * Bootstrap any application services.3 *4 * @return void5 */6public function boot()7{8Vite::macro('image', fn ($asset) => $this->asset("resources/images/{$asset}"));9}1/**2 * Bootstrap any application services.3 *4 * @return void5 */6public function boot()7{8Vite::macro('image', fn ($asset) => $this->asset("resources/images/{$asset}"));9}

Once a macro has been defined, it can be invoked within your templates. For example, we can use the image macro defined above to reference an asset located at resources/images/logo.png:

11Custom Base URLs

If your Vite compiled assets are deployed to a domain separate from your application, such as via a CDN, you must specify the ASSET_URL environment variable within your application's .env file:

1ASSET_URL=https://cdn.example.com1ASSET_URL=https://cdn.example.com

After configuring the asset URL, all re-written URLs to your assets will be prefixed with the configured value:

1https://cdn.example.com/build/assets/app.9dce8d17.js1https://cdn.example.com/build/assets/app.9dce8d17.js

Remember that absolute URLs are not re-written by Vite, so they will not be prefixed.

Environment Variables

You may inject environment variables into your JavaScript by prefixing them with VITE_ in your application's .env file:

1VITE_SENTRY_DSN_PUBLIC=http://example.com1VITE_SENTRY_DSN_PUBLIC=http://example.com

You may access injected environment variables via the import.meta.env object:

1import.meta.env.VITE_SENTRY_DSN_PUBLIC1import.meta.env.VITE_SENTRY_DSN_PUBLICDisabling Vite In Tests

Laravel's Vite integration will attempt to resolve your assets while running your tests, which requires you to either run the Vite development server or build your assets.

If you would prefer to mock Vite during testing, you may call the withoutVite method, which is is available for any tests that extend Laravel's TestCase class:

1use Tests\TestCase; 2  3class ExampleTest extends TestCase 4{ 5public function test_without_vite_example() 6{ 7$this->withoutVite(); 8  9// ...10}11} 1use Tests\TestCase; 2  3class ExampleTest extends TestCase 4{ 5public function test_without_vite_example() 6{ 7$this->withoutVite(); 8  9// ...10}11}

If you would like to disable Vite for all tests, you may call the withoutVite method from the setUp method on your base TestCase class:

1

相关推荐: